﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AppLab.Web;
using System.IO;
using System.Linq;

namespace AppLab.Controls
{
    public class UploadTaskReport : TextBox
    {
        public TaskSubmitData taskSubmitData = new TaskSubmitData();
        public FileInfo selectedFile;

        public UploadTaskReport()
        {
            base.AllowDrop = true;
            base.TextChanged += TextBox_TextChanged;
            base.DragOver += TextBox_DragOver;
            base.DragLeave += TextBox_DragLeave;
            base.Drop += TextBox_Drop;
        }

        void TextBox_KeyDown(object sender, KeyEventHandler e)
        {

        }

        void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (selectedFile != null)
            {
                if (selectedFile.Name != base.Text)
                {
                    taskSubmitData.TestReport = null;
                }
            }
            else
            {
                base.Text = string.Empty;
            }
        }

        private void TextBox_DragOver(object sender, DragEventArgs e)
        {
            base.Background.Opacity = 0.5;
        }

        private void TextBox_DragLeave(object sender, DragEventArgs e)
        {
            base.Background.Opacity = 1;
        }

        private void TextBox_Drop(object sender, DragEventArgs e)
        {
            FileInfo[] sources = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
            if (sources != null && sources.Count() > 0)
            {
                if (sources[0].Exists)
                {
                    selectedFile = sources.First();
                    base.Text = selectedFile.Name;
                    UpdateFileContent(selectedFile);
                }
            }
        }

        public void UpdateFileContent(System.IO.FileInfo fi)
        {
            if (fi.Length > 4 * 1024 * 1024)
            {
                MessageBox.Show("文件不能大于4M！");
                return;
            }

            using (var s = fi.OpenRead())
            {
                var content = new byte[s.Length];
                s.Read(content, 0, (int)s.Length);
                taskSubmitData.TestReport = content;
            }
        }
    }
}
